namespace Stee.CAP8.Communication.Grpc
{
    using System;
    using System.Linq;
    using global::Grpc.Core;
    using global::Grpc.Core.Interceptors;

    public class GrpcClientInterceptor : Interceptor
    {
        private const string TRACEKEY = "x-traceid";
        private readonly string assemblyName;
        public GrpcClientInterceptor(string strAssemblyName)
        {
            assemblyName = strAssemblyName;
        }

        public override AsyncUnaryCall<TResponse> AsyncUnaryCall<TRequest, TResponse>(
            TRequest request, ClientInterceptorContext<TRequest, TResponse> context,
            AsyncUnaryCallContinuation<TRequest, TResponse> continuation)
        {
            if (context.Options.Headers == null)
            {
                var metadata = new Metadata
                {
                    new Metadata.Entry(TRACEKEY, assemblyName)
                };

                var options = context.Options.WithHeaders(metadata);
                context = new ClientInterceptorContext<TRequest, TResponse>(context.Method, context.Host, options);
            }
            else
            {
                var metadataEntry = context.Options.Headers.FirstOrDefault(m => string.Equals(m.Key, TRACEKEY, StringComparison.Ordinal));
                if (metadataEntry == null)
                {
                    context.Options.Headers.Add(TRACEKEY, assemblyName);
                }
                else
                {
                    context.Options.Headers.Remove(metadataEntry);
                    context.Options.Headers.Add(TRACEKEY, $"{metadataEntry.Value}, {assemblyName}");
                }
            }
            return continuation(request, context);
        }

        
    }
}
